package com.hushan.elevator.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hushan.elevator.model.*;
import com.hushan.elevator.security.SecurityUtils;
import com.hushan.elevator.service.*;
import com.hushan.elevator.service.impl.DeviceLogServiceImpl;
import com.hushan.elevator.utils.MinioUtils;
import com.hushan.elevator.utils.Result;
import com.hushan.elevator.utils.ResultCode;
import com.hushan.elevator.vo.*;
import com.hushan.elevator.websocket.server.WebSocketServer;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/device")
public class DeviceController {
    private final DeviceInfoService deviceInfoService;
    private final UserService userService;
    private final DeptService deptService;
    private final MntPersonService mntPersonService;
    private final DeviceMntPersonService deviceMntPersonService;
    @Value("${spring.minio.bucket.deviceImg}")
    private String deviceImgBucket;
    @Resource
    private MinioUtils minioUtils;
    @Autowired
    private DeviceLogService deviceLogService;

    public DeviceController(DeviceInfoService deviceInfoService, UserService userService, DeptService deptService, DeviceMntPersonService deviceMntPersonService, WebSocketServer webSocketServer, MntPersonService mntPersonService) {
        this.deviceInfoService = deviceInfoService;
        this.userService = userService;
        this.deptService = deptService;
        this.deviceMntPersonService = deviceMntPersonService;
        this.mntPersonService = mntPersonService;
    }

    @Operation(summary = "获取所有设备",
            description = "返回本人單位中中所有设备的列表。")
    @GetMapping
    public Result getAllDevices() {
        User requestUser = SecurityUtils.getUser();
        Department requesterDept = deptService.findDeptByUserId(requestUser.getUserId());
        List<DeviceInfo> list = deviceInfoService.findChildDeptDeviceByDeptId(requesterDept.getDeptId());
        List<DeviceInfoTableVo> rst = new ArrayList<>();
        for (DeviceInfo d : list) {
            DeviceInfoTableVo deviceInfoTableVo = new DeviceInfoTableVo();
            BeanUtil.copyProperties(d, deviceInfoTableVo);
            deviceInfoTableVo.setDeptName(deptService.findDeptById(d.getDeptId()).getName());
            deviceInfoTableVo.setDeviceTypeName(deviceInfoService.findType(d).getTitle());
            rst.add(deviceInfoTableVo);
        }
        return new Result(ResultCode.SUCCESS, rst);
    }
    @Operation(summary = "获取所有设备",
            description = "返回本人單位中中所有设备的列表。")
    @GetMapping("/type")
    public Result getDeviceType() {
        return new Result(ResultCode.SUCCESS, deviceInfoService.findTypes());
    }
    @Operation(summary = "根据ID获取设备",
            description = "根据指定的设备ID返回单个设备的详细信息。")
    @GetMapping("/{id}")
    public Result getDeviceById(@PathVariable("id") int id) {
        // detect permission
        User requester = SecurityUtils.getUser();
        boolean permission = deviceInfoService.detectAuthorize(requester,id);
        if (!permission) {
            return new Result(ResultCode.UN_AUTHORISE);
        }
        DeviceInfo deviceInfo = deviceInfoService.findById(id);
//        MntPerson mntPerson = mntPersonService.findByDevice(id);
        DeviceType deviceType = deviceInfoService.findTypeById(id);
        // generate view rst
        DeviceDetailInfoVo rst = new DeviceDetailInfoVo();
        BeanUtil.copyProperties(deviceInfo,rst);
        rst.setDeviceTypeName(deviceType.getTitle());
        rst.setMobile(requester.getTelNumb());
        rst.setAdminName(requester.getTitle());
//        rst.setMntPerson(mntPerson.getName());
//        rst.setMntPersonId(mntPerson.getMntUserId());
//        rst.setMntPersonCompany(mntPerson.getCompany());
        return new Result(ResultCode.SUCCESS,rst);
    }

    @Operation(summary = "新增设备",
            description = "创建一个新的设备记录。请求体中必须包含设备的所有必要信息，如名称、型号等。")
    @PostMapping
    public Result addDevice(@RequestBody DeviceAddVo addVo) {
        // detect requester permission for the device dept
//        User requestUser = SecurityUtils.getUser();
//        boolean permission = deptService.findUserPermissionForDept(requestUser, deptService.findDeptById(addVo.getDeptId()));
//        log.info("用户是否有权限添加设备: {}", permission);
//        if (!permission){
//            return Result.UN_AUTHORISE();
//        }
        // detect serialNumb
//        DeviceInfo deviceInfo = deviceInfoService.findBySerialNumb(addVo.getSerialNumber());
//        if (deviceInfo != null){
//            return new Result(ResultCode.FAIL,"设备序列号已存在");
//        }
        // add deviceInfo
        DeviceInfo info = new DeviceInfo();
        BeanUtil.copyProperties(addVo, info);
        log.info("添加设备信息：{}", info.toString());
        if (info.getLocation()==null){
            info.setLocation("");
        }
        deviceInfoService.add(info);

        // add device & mntPerson connect
//        DeviceMntPerson deviceMntPerson = new DeviceMntPerson();
//        deviceMntPerson.setUserRolePK(new DeviceMntPersonPK(info.getDeviceId(), addVo.getMntPersonId()));
//        deviceMntPerson.setCreatedBy(requestUser.getUserId());
//        deviceMntPersonService.addDeviceMntPerson(deviceMntPerson);
        return new Result(ResultCode.SUCCESS);
    }

    @Operation(summary = "修改设备",
            description = "根据提供的设备ID和新的设备信息来更新设备记录。请求体中必须包含完整的设备信息，包括但不限于设备名称、型号、状态等。如果设备ID不存在，则返回错误信息。")
    @PutMapping("/{id}")
    public Result updateDevice(@PathVariable("id") int id, @RequestBody DeviceAddVo updateData) {
        if (deviceInfoService.findById(id) == null) {
            return Result.ERROR();
        }
        boolean permission = deviceInfoService.detectAuthorize(id);
        if (!permission) {
            return Result.UN_AUTHORISE();
        }
        DeviceInfo deviceInfo = deviceInfoService.findById(id);
        BeanUtil.copyProperties(updateData, deviceInfo);
        deviceInfoService.update(deviceInfo);
        return new Result(ResultCode.SUCCESS);
    }

    @Operation(summary = "根据部门ID获取全部设备",
            description = "根据指定的部门ID返回该部门下所有设备的列表。")
    @GetMapping("/dept/{deptId}")
    public Result getAllDevicesByDeptId(@PathVariable("deptId") int deptId) {
        User requestUser = SecurityUtils.getUser();
        boolean permission = deptService.findUserPermissionForDept(requestUser, deptId);
        if (!permission) {
            return Result.UN_AUTHORISE();
        }


        List<DeviceInfo> list = deviceInfoService.findChildDeptDeviceByDeptId(deptId);
        List<DeviceInfoTableVo> rst = new ArrayList<>();
        for (DeviceInfo d : list) {
            DeviceInfoTableVo deviceInfoTableVo = new DeviceInfoTableVo();
            BeanUtil.copyProperties(d, deviceInfoTableVo);
            deviceInfoTableVo.setDeptName(deptService.findDeptById(d.getDeptId()).getName());
            rst.add(deviceInfoTableVo);
        }
        return new Result(ResultCode.SUCCESS, rst);
    }

    @Operation(summary = "删除设备",
            description = "根据指定的设备ID删除对应的设备记录。如果设备ID不存在，则返回错误信息。")
    @DeleteMapping("/{id}")
    public Result deleteDevice(@PathVariable("id") int id) {
        if (deviceInfoService.findById(id) == null) {
            return Result.ERROR();
        }
        boolean permission = deviceInfoService.detectAuthorize(id);
        if (!permission) {
            return Result.UN_AUTHORISE();
        }
        deviceInfoService.delete(id);

        return new Result(ResultCode.SUCCESS);
    }

    @Operation(summary = "删除多个设备",
            description = "根据指定的设备ID列表删除对应的设备记录。如果设备ID不存在，则返回错误信息。")
    @DeleteMapping("")
    public Result deleteDevice(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            if (deviceInfoService.findById(id) == null) {
                return Result.ERROR();
            }
            boolean permission = deviceInfoService.detectAuthorize(id);
            if (!permission) {
                return Result.UN_AUTHORISE();
            }
            deviceInfoService.delete(id);
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Operation(summary = "根据ID获取设备最新照片",
            description = "根据ID获取设备最新照片。")
    @RequestMapping(value = "/img/{id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getDeviceImgById(@PathVariable("id") int id) throws IOException {
        DeviceInfo deviceInfo = deviceInfoService.findById(id);
        ResponseEntity<byte[]> download = minioUtils.download(deviceInfo.getSerialNumber() + ".jpg", deviceImgBucket);
        if (download==null)return null;
        return download.getBody();
    }


}
